let elementId = '';
let currentElement = '';
function pompt() {
  elementId = prompt(
    "Input section('-all' for download all)：",
    "Word List L1 - L7"
  );
  currentElement = document.querySelector(`li[aria-label="${elementId}"]`);
  console.log(currentElement);
}

function courseDownload(url, filename) {
  getBlob(url, function (blob) {
    saveAs(blob, filename);
  });
}

function getBlob(url, cb) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'blob';
  xhr.onload = function () {
    if (xhr.status === 200) {
      cb(xhr.response);
    }
  };
  xhr.send();
}

function saveAs(blob, filename) {
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, filename);
  } else {
    var link = document.createElement('a');
    var body = document.querySelector('body');
    link.href = window.URL.createObjectURL(blob);
    link.download = filename;
    link.style.display = 'none';
    body.appendChild(link);
    link.click();
    body.removeChild(link);
    window.URL.revokeObjectURL(link.href);
  }
}

function elementDownload(element) {
  let _id = element.id;
  let _sectionName = document
    .querySelector(`#${_id} .hidden.sectionname`)
    .innerText.replace('.', '');
  [].slice
    .call(document.querySelectorAll(`#${_id} a[href*='/resource']`))
    .map((z, index) => {
      if (z['onclick']) {
        try {
          setTimeout(() => {
            courseDownload(
              z.href + '&redirect=1',
              `[${_sectionName}]-${z.text.replace(' Datei', '')}`
            );
          }, 1000 * index);
        } catch (z) {}
      }
    });
}
function main() {
  pompt();
  if (elementId === '-all') {
    [...document.querySelectorAll('li[id^=section]')].forEach((e) => {
      elementDownload(e);
    });
  } else {
    if (currentElement == null) {
      alert('Wrong section!');
      return;
    }
    elementDownload(currentElement);
  }
}
main();
